﻿using System;
using AutoStopApp.Core;
using AutoStopData.BussinessLogic;
using AutoStopData.Domains;
using AutoStopData.Model;
using Telerik.Web.UI;

namespace AutoStopApp.Controls
{
    public partial class UserRegister : AjaxUserControl
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            btnSave.Click += BtnSaveClick;
            Load += PageLoad;
        }

        protected void PageLoad(object sender, EventArgs e)
        {
            AddAjaxSetting(btnSave, pnlRegistration);
            if (!IsPostBack)
            {
                FillUserTypeCodes();
            }
        }

        void BtnSaveClick(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var existingUser = Users.GetByMail(txtMail.Text);
                if (existingUser != null)
                {
                    lblValidationError.Text = "Zadaný mail je už zaregistrovaný";
                }
                else
                {
                    var user = new User
                                   {
                                       Name = txtName.Text,
                                       Mail = txtMail.Text,
                                       Contact = txtContact.Text,
                                       Password = txtPassword1.Text,
                                       UserTypeCode = cbxUserType.SelectedValue
                                   };
                    Users.Insert(user);
                    pnlFormData.Visible = false;
                    pnlSuccess.Visible = true;
                }


            }
            else
            {
                lblValidationError.Text = "Vyplňte všetky potrebné polia";
            }

        }

        private void FillUserTypeCodes()
        {
            var userTypes = UserTypes.All();
            foreach (var userType in userTypes)
            {
                if (userType.UserTypeCode != UserTypes.GetCode(UserTypes.Name.Administrator))
                {
                    cbxUserType.Items.Add(new RadComboBoxItem(userType.LocalizedName, userType.UserTypeCode));
                }
            }
        }
    }
}